package com.lxl.bt.retorfit;

import android.text.TextUtils;
import android.util.Log;

import com.lxl.bt.BuildConfig;
import com.lxl.bt.bean.LogoutMessage;
import com.lxl.bt.net.Result;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @Author : xinlong.lv
 */
public abstract class NetCallback<T> implements Callback<T>, LifecycleObserver {

    private static final String TAG = NetCallback.class.getSimpleName();

    private boolean isDestroy = false;

    /**
     * 生命周期 onDestroy
     */
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private void onDestroy(LifecycleOwner owner) {
        isDestroy = true;
        owner.getLifecycle().removeObserver(this);
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (isDestroy) {
            onFinish();
            return;
        }
        if (response.isSuccessful()) {
            success(response.body());
        } else {
            responseError(response);
            int code = response.code();
            if (401 == code){
                EventBus.getDefault().post(new LogoutMessage());
            }
        }
        onFinish();
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        t.printStackTrace();
        onError(t.getMessage());
        onFinish();
    }


    private void responseError(Response<T> response) {
        try {
            ResponseBody body = response.errorBody();
            if (body == null) {
                onError("Unknown Error");
            } else {
                onError(new Gson().fromJson(body.string(), Result.class));
            }
//            onError(body == null ? "Unknown Error" : body.string());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public abstract void onSuccess(T result);

    public abstract void netLogin();

    private void success(T result) {
        if (((Result) result).isSuccess()) {
            onSuccess(result);
        } else if ("0".equals(((Result) result).getErrorCode())) {
            //netLogin();
            EventBus.getDefault().post(new LogoutMessage());
        } else {
            onError((Result) result);
        }
    }

    public void onError(String errorStr) {

    }

    public void onError(Result result) {
        if (BuildConfig.DEBUG) {
            Log.e(TAG, "onError: result======" + new Gson().toJson(result));
        }
        onError(!TextUtils.isEmpty(result.getMsg()) ? result.getMsg() : result.getMessage());
    }


    public void onFinish() {

    }

}